package logic

import (
	"context"

	"googee/common/errorx"
	"googee/service/leaderboard/api/internal/svc"
	"googee/service/leaderboard/api/internal/types"
	"googee/service/leaderboard/rpc/types/leaderboard"

	"github.com/zeromicro/go-zero/core/logx"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

type RankuserLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRankuserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RankuserLogic {
	return &RankuserLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RankuserLogic) Rankuser(req *types.RankUserReq) (resp *types.RankUserReply, err error) {
	resp = &types.RankUserReply{}
	resp.Data.BatchId = req.BatchId
	resp.Data.Rank = -1
	resp.Data.Bid = req.Bid

	result, err := l.svcCtx.Leaderboard.GetRankForUser(l.ctx, &leaderboard.UserRequest{
		UserId:      req.UserId,
		Bid:         req.Bid,
		Dense:       false,
		Batchid:     req.BatchId,
		BatchOffset: req.BatchOffset,
	})

	if err != nil {
		st, ok := status.FromError(err)
		if ok {
			if st.Code() == codes.NotFound {
				return nil, errorx.NewCodeErrorNoMsg(errorx.LEADERBOARD_ERROR + 1)
			} else if st.Code() == codes.Internal {
				return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
			}
		} else {
			return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, "系统内部未知错误")
		}
	}

	resp.Data.BatchId = result.Batchid
	resp.Data.Rank = result.Rank

	return
}
